using Gateway.IQuery;
using Gateway.IQuery.Tenant;
using Gateway.IQuery.Tenant.Request;
using Gateway.IQuery.Tenant.Result;
using Gateway.IRepositories;
using SqlSugar;

namespace Gateway.Query;

/// <summary>
/// 
/// </summary>
public class TenantQuery : ITenantQuery
{
    private readonly IQueryRepository _queryRepository;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="queryRepository"></param>
    public TenantQuery(IQueryRepository queryRepository)
    {
        _queryRepository = queryRepository;
    }

    /// <summary>
    /// 获取分页列表
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<PageResult<TenantDetailResult>> GetPageList(TenantPageListRequest request)
    {
        RefAsync<int> total = 0;
        var data = await _queryRepository.Db.Queryable<TenantDetailResult>()
            .WhereIF(
                !string.IsNullOrEmpty(request.QueryKey) && request.QueryKey.Equals("code") &&
                !string.IsNullOrEmpty(request.QueryValue), x => x.TenantCode.Equals(request.QueryValue))
            .WhereIF(
                !string.IsNullOrEmpty(request.QueryKey) && request.QueryKey.Equals("name") &&
                !string.IsNullOrEmpty(request.QueryValue), x => x.TenantName.Contains(request.QueryValue))
            .WhereIF(
                !string.IsNullOrEmpty(request.QueryKey) && request.QueryKey.Equals("alias") &&
                !string.IsNullOrEmpty(request.QueryValue), x => x.TenantAliasName.Contains(request.QueryValue))
            .ToPageListAsync(request.Page, request.PageSize, total);
        return PageResult<TenantDetailResult>.Create(data, total);
    }

    /// <summary>
    /// 获取详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<TenantDetailResult> GetDetail(string id)
    {
        return await _queryRepository.FindAsync<TenantDetailResult>(x => x.TenantId == id);
    }
}